package com.aier.controller.inventory;

import com.aier.bean.inventory.InventoryRecordsBean;
import com.aier.excel.FreezeRowColHandler;
import com.aier.service.inventory.InventoryRecordsService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 根据商品录入记录，与excel相关的controller
 */
@Controller
public class InventoryRecordsController {
    @Resource
    private InventoryRecordsService inventoryRecordsService;

    @RequestMapping("/download_inventory_excel")
    public void downloadExcel(HttpServletResponse response) throws UnsupportedEncodingException {
        ExcelWriter excelWriter = null;
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("11", "UTF-8").replaceAll("\\+", "%20");
            Map<String, List<InventoryRecordsBean>> recordsTableMap = inventoryRecordsService.buildInventoryRecordsTable();
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里 需要指定写用哪个class去写
            excelWriter = EasyExcel.write(response.getOutputStream(),InventoryRecordsBean.class).build();
            int index = 0;
            for (Map.Entry<String, List<InventoryRecordsBean>> entry : recordsTableMap.entrySet()) {
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                WriteSheet writeSheet = EasyExcel.writerSheet(index, entry.getKey())
                        .registerWriteHandler(new FreezeRowColHandler(0,2,0,2))
                        .build();

                excelWriter.write(entry.getValue(), writeSheet);
                index++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (excelWriter != null){
                excelWriter.finish();
            }
        }
    }
}
